package logic

import (
	"news/dao/mysql"
	"news/models"
	"news/pkg/snowflake"

	"go.uber.org/zap"
)

func CreateComment(p *models.Comment) (err error) {
	p.CommentID = (snowflake.GenID())
	err = mysql.CreateComment(p)
	if err != nil {
		zap.L().Error("mysql.CreateComment(p) failed", zap.Error(err))
		return err
	}
	return
}

// 获取列表的全部评论数据
func GetCommentList(page, size int64) (data []*models.CommentDetail, err error) {
	commentList, err := mysql.GetCommentList(page, size)
	if err != nil {
		zap.L().Error("mysql.GetCommentList failed", zap.Error(err))
		return
	}
	data = make([]*models.CommentDetail, 0, len(commentList)) // data 初始化
	for _, post := range commentList {
		//根据作者ID 获取作者信息
		user, err := mysql.GetUserByID(post.AuthorId)
		if err != nil {
			zap.L().Error("mysql.GetUserByID(post.AuthorId) failed",
				zap.Int64("authorID", post.AuthorId), zap.Error(err))
			continue
		}
		postDetail := &models.CommentDetail{
			AuthorId:   post.AuthorId,
			Status:     post.Status,
			AuthorName: user.Username,
			Content:    post.Content,
			CreateTime: post.CreateTime,
		}
		// 接口数据拼接
		data = append(data, postDetail)
	}
	return
}
